package com.qingsong.component;


import com.auth0.jwt.exceptions.TokenExpiredException;
import com.qingsong.exception.ServiceException;
import com.qingsong.result.Result;
import com.qingsong.result.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.rmi.ServerException;

@Slf4j
@RestControllerAdvice(basePackages = {"com.qingsong.controller"})
public class ExceptionAdvice {  
  
    @ExceptionHandler(ServiceException.class)
	public Object serviceException(ServiceException e) {

	    log.error("业务异常:" + e.getMessage());
	    
	    // 响应  
	    return new Result<>(ResultCode.FAILED, e.getMessage());
	}

	@ExceptionHandler(TokenExpiredException.class)
	public Object TokenExpiredException(TokenExpiredException e) {

		log.error("Token异常:" + e.getMessage());

		// 响应
		return new Result<>(ResultCode.TOKEN_FAILED, e.getMessage());
	}

	@ExceptionHandler(MethodArgumentNotValidException.class)
	public Object methodArgumentNotValidException(MethodArgumentNotValidException e) {

		// 获取bindingResult中所有属性错误信息集合中的第一个属性错误
		FieldError firstFieldError = e.getBindingResult().getFieldErrors().get(0);

		// 异常信息 : "xxx实例的xxx属性校验失败: xxx异常信息"
		String message = String.format("%s实例的%s属性校验失败: %s",
				firstFieldError.getObjectName(),
				firstFieldError.getField(),
				firstFieldError.getDefaultMessage());

		// 记录日志
		log.error(message);

		// 响应
		return new Result<>(ResultCode.VALIDATE_FAILED, message);
	}

	@ExceptionHandler(DuplicateKeyException.class)
	public Object duplicateKeyException(DuplicateKeyException e) {
		String msg = e.getMessage();
		if(msg != null){
			msg = msg.substring(msg.indexOf("entry") + 6, msg.indexOf("' for")) + "已存在";
		}
		log.error("约束异常: " + msg);
		return new Result<>(ResultCode.FAILED, msg);
	}

	@ExceptionHandler(Exception.class)
	public Object exception(Exception e){
		log.error("其他异常:" + e.getMessage());
		return new Result<>(ResultCode.FAILED,e.getMessage());
	}
}